﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;

namespace ToyundaPhone.Pages
{
	public partial class FavoritesPage : PhoneApplicationPage, System.ComponentModel.INotifyPropertyChanged
	{
		private Helpers.PlaylistEnumHelper plEnumHelper;

		public FavoritesPage()
		{
			InitializeComponent();
			Songs = from s in (Application.Current as App).SongDatabase.Songs where s.Favorite == true select s;
			plEnumHelper = new Helpers.PlaylistEnumHelper(e => Dispatcher.BeginInvoke(() => OnPropertyChanged("Playlists")), songList);
			Playlists = plEnumHelper.GetEnumerator();
			plEnumHelper.NotifyUpdate();
		}

		#region INotifyPropertyChanged Members

		public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

		#endregion

		public IEnumerable<ToyundaPhone.Database.Song> Songs { get; private set; }
		public IEnumerable<Database.Playlist> Playlists { get; private set; }

		private void OnPropertyChanged(string propertyName)
		{
			if (PropertyChanged != null)
			{
				PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
			}
		}

		private void SongList_ListUpdated(object sender, EventArgs e)
		{
			var tmp = Songs;
			Songs = null;
			OnPropertyChanged("Songs");
			Songs = tmp;
			OnPropertyChanged("Songs");
		}

		private void Empty_Click(object sender, EventArgs e)
		{
			if (MessageBox.Show("Êtes-vous sûr de vouloir vider vos favoris ?", "Favoris", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
			{
				foreach (var song in Songs)
				{
					song.Favorite = false;
				}
				(Application.Current as App).SongDatabase.SubmitChanges();
				var tmp = Songs;
				Songs = null;
				OnPropertyChanged("Songs");
				Songs = tmp;
				OnPropertyChanged("Songs");
			}
		}

		private void Playlists_Click(object sender, EventArgs e)
		{
			NavigationService.Navigate(new Uri("/playlists", UriKind.Relative));
		}

		Action _playlistSelectCallback = null;

		private void SongList_SelectPlaylist(object sender, Controls.SelectPlaylistEventArgs e)
		{
			_playlistSelectCallback = e.Callback;
			listPicker.Open();
		}

		private void ChooseList_Click(object sender, EventArgs e)
		{
			_playlistSelectCallback = null;
			listPicker.Open();
		}

		private void ListPicker_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
		{
			songList.Playlist = listPicker.SelectedItem as Database.Playlist;
			if (_playlistSelectCallback != null)
				_playlistSelectCallback();
		}

		private void PhoneApplicationPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
		{
			Microsoft.Phone.Shell.SystemTray.SetIsVisible(this, e.Orientation == PageOrientation.Portrait || e.Orientation == PageOrientation.PortraitUp || e.Orientation == PageOrientation.PortraitDown);
		}
	}
}